/**
 * Created by Mark_ren on 2017/5/22.
 * 苟富贵,無相忘
 * Update by Mark_ren on 2017/5/23.
 * 今天心情不好，可能是因为阴天。
 */
var moment = require("moment");
var co = require('co');
var seqModule = require('../../../routes/createModules');
var seq = new seqModule();
var util = require('../../../common/util');
var formidable = require('formidable');
var fs = require('fs');
var request = require('request');
var nodeExcel = require('excel-export')
var EventProxy = require('eventproxy');
var xlsx = require('node-xlsx');
var articleController = {

    /**
     *  危重症时间 后台接口
     * @param req
     * @param res
     */
    getJWArticleList: function (req, res) {
        co(function () {
            var page = parseInt(req.query.page);
            var params = {};
            var paramT = {};
            //根据id
            if (req.query.id != undefined) {
                params["id"] = req.query.id;
            }
            if (req.query.item != undefined) {
                params["item"] = req.query.item;
            }
            if (req.query.sort != undefined) {
                params["sort"] = req.query.sort;
            }
            if (req.query.type != undefined) {
                params["type"] = req.query.type;
            }
            //模糊查询
            if (req.query.title != undefined) {
                params["title"] = { "$like": "%" + req.query.title + "%" };
            }
            paramT["where"] = params;
            paramT["order"] = [["topTime", 'DESC'], ["createTime", 'DESC']];
            if (req.query.page != undefined && req.query.rows != undefined) {
                paramT["offset"] = parseInt(req.query.page);
                paramT["limit"] = parseInt(req.query.rows);
            }
            seq.articleModule.findAndCountAll(paramT).then(function (result) {
                res.json({ "success": true, "page": page, "total": result.count, "result": result.rows });
            });
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '查询失败' });
            console.log(e);
        })


    },

    /**
     *  增加急危医频道图文
     * @param req
     * @param res
     */
    addArticle: function (req, res) {
        co(function () {

            var uuid = util.getUUID();
            if (req.method.toLowerCase() == 'post') {
                // parse a file upload
                var form = new formidable.IncomingForm();
                //files = [],
                //fields = [];
                form.uploadDir = "public/data/articleCover";
                form.type = true;
                form.on("progress", function (bytesReceived, bytesExpected) {
                    console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                    // 百分比
                    var percent = Math.round(bytesReceived / bytesExpected * 100);
                    console.log("percent:" + percent + "%");
                    // 存入
                    //sessions.setSession(req,res,opts);
                });
                form.parse(req, function (err, fields, files) {
                    // res.render('index', { paths: [files.upload.name] });
                    if (files.pUrl != null) {
                        var imgType = files.pUrl.name.split(".");
                        if (fields.item == 3) {
                            files.pUrl.name = "jwypd_" + moment().format("YYYYMMDDHHmmss" + "." + imgType[imgType.length - 1]);
                        } else if (fields.item == 4) {
                            files.pUrl.name = "czypd_" + moment().format("YYYYMMDDHHmmss" + "." + imgType[imgType.length - 1]);
                        } else if (fields.item == 6) {
                            files.pUrl.name = "subjectSet_" + moment().format("YYYYMMDDHHmmss" + "." + imgType[imgType.length - 1]);
                        }

                        fs.renameSync(files.pUrl.path, form.uploadDir + "/" + files.pUrl.name);
                        fields.titlePic = files.pUrl.name;
                    }


                    fields.id = uuid;
                    fields.createTime = util.getNowTime();
                    fields.topTime = util.getNowTime();
                    seq.articleModule.create(fields).then(function (results) {
                        console.log(fields.item);
                        if (fields.sort == 301) {
                            res.redirect(util.getIP() + "wzzTime/jwypdList.html?item=" + fields.item + "&sort=" + fields.sort);
                        } else if (fields.sort == 401) {
                            res.redirect(util.getIP() + "nxgTime/czypdList.html?item=" + fields.item + "&sort=" + fields.sort);
                        } else if (fields.sort == 601) {
                            res.redirect(util.getIP() + "subjectSet/keshixunliList.html?item=" + fields.item + "&sort=" + fields.sort);

                        } else if (fields.sort == 602) {
                            res.redirect(util.getIP() + "subjectSet/keyanjiayouzhanList.html?item=" + fields.item + "&sort=" + fields.sort);

                        } else if (fields.sort == 603) {
                            res.redirect(util.getIP() + "subjectSet/lianheguoList.html?item=" + fields.item + "&sort=" + fields.sort);

                        }

                    });
                });
            }
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '添加失败' });
            console.log(e);
        })

    },

    /**
     *  更新急危医频道图文
     * @param req
     * @param res
     */
    updArticle: function (req, res) {
        co(function () {
            if (req.method.toLowerCase() == 'post') {
                // parse a file upload
                var form = new formidable.IncomingForm();
                //files = [],
                //fields = [];
                form.uploadDir = "public/data/articleCover";
                form.type = true;

                form.on("progress", function (bytesReceived, bytesExpected) {
                    console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                    // 百分比
                    var percent = Math.round(bytesReceived / bytesExpected * 100);
                    console.log("percent:" + percent + "%");
                    // 存入
                    //sessions.setSession(req,res,opts);
                });
                form.parse(req, function (err, fields, files) {
                    // res.render('index', { paths: [files.upload.name] });
                    var params = {};
                    var paramT = {};
                    if (files.pUrl != null && files.pUrl.name != "") {
                      
                        var imgType = files.pUrl.name.split(".");
                        if (fields.item == 3) {
                            files.pUrl.name = "jwypd_" + moment().format("YYYYMMDDHHmmss" + "." + imgType[imgType.length - 1]);
                        } else if (fields.item == 4) {
                            files.pUrl.name = "czypd_" + moment().format("YYYYMMDDHHmmss" + "." + imgType[imgType.length - 1]);
                        } else if (fields.item == 6) {
                            files.pUrl.name = "subjectSet_" + moment().format("YYYYMMDDHHmmss" + "." + imgType[imgType.length - 1]);
                        }
                        fs.renameSync(files.pUrl.path, form.uploadDir + "/" + files.pUrl.name);
                        params["titlePic"] = files.pUrl.name;
                    }
                    var paramU = { 'id': req.params.ID };

                    if (fields.title != undefined) {
                        params["title"] = fields.title;
                    }
                    if (fields.URL != undefined) {
                        params["URL"] = fields.URL;
                    }
                    if (fields.type != undefined && fields.type != "") {
                        params["type"] = parseInt(fields.type);
                    }

                    paramT["where"] = paramU;

                    seq.articleModule.update(params, paramT).then(function (results) {

                        if (fields.sort == 301) {
                            res.redirect(util.getIP() + "wzzTime/jwypdList.html?item=" + fields.item + "&sort=" + fields.sort);
                        } else if (fields.sort == 401) {
                            res.redirect(util.getIP() + "nxgTime/czypdList.html?item=" + fields.item + "&sort=" + fields.sort);
                        } else if (fields.sort == 601) {
                            res.redirect(util.getIP() + "subjectSet/keshixunliList.html?item=" + fields.item + "&sort=" + fields.sort);

                        } else if (fields.sort == 602) {
                            res.redirect(util.getIP() + "subjectSet/keyanjiayouzhanList.html?item=" + fields.item + "&sort=" + fields.sort);

                        } else if (fields.sort == 603) {
                            res.redirect(util.getIP() + "subjectSet/lianheguoList.html?item=" + fields.item + "&sort=" + fields.sort);

                        }

                    });
                });
            }
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '修改失败' });
            console.log(e);
        })

    },

    /**
     * 根据 ID 更新图文TOP时间
     * @param {*} req
     * @param {*} res
     */
    setArticleTop: function (req, res) {
        co(function () {
            var params = {};
            var paramT = {};
            var paramU = { 'id': req.query.id };

            params["topTime"] = util.getNowTime();

            paramT["where"] = paramU;
            seq.articleModule.update(params, paramT).then(function (results) {
                res.json({ "success": true, "msg": "修改成功", "result": results });
            });
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '修改失败' });
            console.log(e);
        })

    },

    /**
     * 根据 ID 删除图文
     * @param {*} req
     * @param {*} res
     */
    deleteByID: function (req, res) {
        var params = req.query.params;
        var arr = params.split(",");
        try {
            seq.articleModule.destroy({
                where: {
                    'id': [arr]
                }
            }).then(function (result) {
                res.status(200).json({
                    message: "删除成功！",
                    success: true
                });
            })
        } catch (err) {
            res.status(500).json({
                message: "服务错误！",
                err: err
            });
        }
    },
    exportExcel: function (req, res) {
        var accessToken = req.query.accessToken;
        var vac = [["图文标题", "图文链接"]]
        var jsonData = {
            "type": "news",
            "offset": 0,
            "count": 93
        };
        request({
            url: "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + accessToken,
            method: "post",
            json: true,
            headers: {
                "content-type": "application/json",
            },
            body: jsonData
        },
            function (error, response, data) {
                if (!error && response.statusCode == 200) {
                    var strData = JSON.stringify(data);
                    var jsonData = JSON.parse(strData);
                    var JsonArr = jsonData.item;
                    console.log(strData);
                    for (var i = 0; i < JsonArr.length; i++) {
                        var resultArr = JsonArr[i].content.news_item;
                        for (var j = 0; j < resultArr.length; j++) {
                            var val = resultArr[j];
                            var temp = new Array();
                            temp[0] = val.title + "";
                            temp[1] = val.url || "";
                            vac.push(temp);
                        }
                    }
                    var buffer = xlsx.build([{ name: "articleExport", data: vac }]);
                    fs.writeFileSync('public/data/articleExport93.xlsx', buffer, 'binary');

                } else {
                    res.json({ 'success': false, 'msg': '请求失败' });
                }
            }).catch(function (e) {
                res.json({ 'success': false, 'msg': '添加失败' });
                console.log(e);
            })




    }



}
module.exports = articleController;

